<?php

namespace backend\controllers;

use Yii;
use backend\models\VipRefund;
use backend\models\VipRefundSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use backend\models\PayTrade;
use liangzoe\payment\weixin;
use liangzoe\payment\alipay;
use backend\models\LogPay;
use yii\web\ForbiddenHttpException;
use common\models\UserInfo;
use backend\models\Image;
use yii\web\UploadedFile;
use liangzoe\payment\vip_alipay;

/**
 * LogRefundController implements the CRUD actions for LogRefund model.
 */
class VipRefundController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }
    /*权限*/
   	public function beforeAction($action)
    {
    	//如果未登录，则直接跳转
    	$action = Yii::$app->controller->action->id;
    	$controller = Yii::$app->controller->id;
    	if($action != 'alipay-refund-notify' && $action != 'weixin-refund'){//支付宝回调页面不限制   	
	    	if(Yii::$app->user->isGuest){
	    		return $this->redirect(['/site/login']);
	    	}
	    
	    	 
	    	
	     
	     if(\Yii::$app->user->can('log-refund')){
	    		return true;
	    	}else{
	    		throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permissions'));
	    	}  
	    	
	    	
    	}
    	else{
    		return true;
    	}
    }
    /**
     * Lists all LogRefund models.
     * @return mixed
     */
    public function actionIndex()
    {
    	/*查询微信的退款信息*/
    	$logrefund = new VipRefund();
    	$logrefund->weixin_notify();
    	
    	$searchModel = new VipRefundSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single LogRefund model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new LogRefund model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new VipRefund();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->refund_id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing LogRefund model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->refund_id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing LogRefund model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the LogRefund model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return LogRefund the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = VipRefund::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    /*
     * 添加退款*/
    public function actionAdd($trade_id){
    	
    	$trade_model = PayTrade::find()->where("id={$trade_id}")->with(['logPayInfo'])->one();
    	$if_exist = LogRefund::findOne(['trade_no'=>$trade_model->trade_no]);
    	
    	if(!empty($if_exist)) return '退款申请失败:退款记录已存在，不能重复申请';
    	if($trade_model['refund_price'] < 0.01) return '退款申请失败:退款金额不能为0';
    	
    	//支付数与退款数一致
    	$condition = "trade_no='{$trade_model->trade_no}' and state in (1,2)";
    	$log_pay = LogPay::find()->where($condition)->all();
    	if(empty($log_pay))	return '不存在支付信息，不能申请退款'.$condition;
    	//计算实际支付的金额
    	$real_pay=0;
    	foreach ($log_pay as $key => $v){
    		$real_pay += $v['rmb'];
    	}
    	
    	$count = count($log_pay);
    	$percent = round($real_pay / $trade_model['refund_price'],2);
    	foreach ($log_pay as $val){	
	    	//新增退款申请
	    	$refund_model = new LogRefund();
	    	$refund_model->rmb = round($val->rmb * $percent , 2);//退款金额
	    	$refund_model->refund_no = date('YmdHis',$trade_model->refund_time).$trade_model->refund_time.rand(10, 99);
	    	$refund_model->doing = 2;//客服主管
	    	$refund_model->done_list = "客服申请退款|".Yii::$app->user->identity->username.
	    								"(".Yii::$app->user->identity->id.")|".date('Y-m-d H:i:s',time());
	    	$refund_model->transaction_id = str_replace(['wx','zfb_'], ['',''], $val->transaction_id);
	    	$refund_model->trade_no =$val->trade_no;
	    	$refund_model->uid =$val->uid;
	    	$refund_model->type =$val->type;//退款的方式与付款方式一样
	    	$refund_model->state =1;//客服退款申请
	    	$refund_model->memo_xml ='';
	    	$refund_model->addtime = time();
	    	$add = $refund_model->save();
    	}
    	if($add){
    		$trade_model->refund_audit=1;
    		
    		//$update_logistics = PayLogistics::updateAll(['logistics_state'=>3],"trade_id={$trade_id}");
    		if($trade_model->save()){
    			return '退款申请成功:进入退款流程，请去退款页面操作';
    		}
    	}
    	return '退款申请失败:请联系管理员';
    	    	
    }
    public function actionAudit($refund_id){
    	$model = $this->findModel($refund_id);
    	$model->doing = 3;
    	$model->state = 2;
    	$model->done_list .= "，主管同意退款|".Yii::$app->user->identity->username.
    								"(".Yii::$app->user->identity->id.")|".date('Y-m-d H:i:s',time());
    	if($model->save()){
    		return '已同意退款';
    	}
    	return '审核退款失败';
    	
    	
    }
    /*提交退款申请到支付平台*/
    public function actionApply($refund_ids){
    	
    	$refund = $this->_refund_data($refund_ids);
    	$weixin = $refund['weixin'];
    	$alipay = $refund['alipay'];
    	if(!empty($weixin)){
    		foreach ($weixin as $key=>$val){
    			$payment_weixin = new weixin();
    			$result = $payment_weixin->get_refundform($val);
    			if($result){
    			    $update_refund = VipRefund::findOne(['refund_no'=>$result['out_refund_no']]);
    			    if($result['result_code'] == 'SUCCESS'){//退款申请接收成功
    			        $update_refund->state = 10;//退款中
    			        $update_refund->starttime = time();
    			        $update_refund->third_refund_no = $result['refund_id'];
    			        $update_refund->save();
    			        
    			        /*查询微信的退款信息*/
    			        $uid=$update_refund->uid;
    			        $logrefund = new VipRefund();
    			        $logrefund->weixin_notify();
    			        
    			        echo '微信退款成功';
    			    }
    			}else{
    			    echo '   微信退款失败<br/> ';
    			}
    			
    		}
    		
    	}
    	if(!empty($alipay)){
    		$payment_alipay = new alipay();
            $payment_alipay->setRefundUrl("paynotify-viprefund-notify-");
    		$refund_form = $payment_alipay->get_refundform($alipay);
    		if($refund_form){
    			VipRefund::updateAll(['zfb_batch_no'=>"{$alipay['batch_no']}","state"=>10,"starttime"=>time()],
    			"refund_id in ({$alipay['refund_ids']})");
    		}
    		echo $refund_form;
    	}
    	//return '已提交退款申请到支付平台';
    }
    public function _refund_data($refund_ids){
    	$refund_model = VipRefund::find()->where("refund_id in ({$refund_ids})")->with(['logPayVipInfo'])->all();
    	
    	$alipay_data = array();
    	$alipay_refund_ids = array();
    	$weixin_data = array();
    	foreach ($refund_model as $key => $val){
    		if($val->type == '1'){//微信
    			$_row['transaction_id'] = $val['transaction_id'];//支付平台交易号
    			$_row['out_refund_no']  = $val['refund_no'];//商户退款号
    			$_row['total_fee'] = intval($val->logPayVipInfo->rmb * 100);
    			$_row['refund_fee'] = intval($val->rmb * 100);
    			$_row['refund_id'] = $val['refund_id'];
    			array_push($weixin_data, $_row);
    		}elseif($val->type == '2'){//支付宝    			
    			$_detail_data = $val->transaction_id.'^'.$val->rmb.'^'.'用户申请退款';
    			array_push($alipay_refund_ids, $val['refund_id']);
    			array_push($alipay_data, $_detail_data);
    		}
    	}
		if(!empty($alipay_data))
	    	$alipay_data = array(
	    			'refund_ids'=> implode(',',$alipay_refund_ids),
	    			'refund_date'=> date('Y-m-d H:i:s',time()),	
	    			'batch_no'=>date('YmdHis',time()).mt_rand(10000, 99999),//alipay批量号
	    			'batch_num'=>count($alipay_data),
	    			'detail_data'=>implode('#', $alipay_data),
	    	);
		
		$return['alipay']=$alipay_data;
		$return['weixin'] = $weixin_data;
    	return $return;
    }
    //支付宝的通知信息
    function actionAlipayRefundNotify(){
    	if($_POST) $request = $_POST;
    	else $request = $_GET;
    	
    	$logrefund = new VipRefund();
    	$notify = $logrefund->alipay_notify($request);
    }
    //微信的查询信息
    public function actionWeixinRefund(){
    	$logrefund = new VipRefund();
    	$logrefund->weixin_notify();
    }
    
    /*财务报表*/
    public function actionFinanceRefund()
    {
    	$searchModel = new LogRefundSearch();
    	$res = $searchModel->reportSearch(Yii::$app->request->queryParams);
    	//运营的信息
    	$user_model = UserInfo::get_type_user("5");
    	return $this->render('finance_report', [
    			'searchModel' => $searchModel,
    			'dataProvider' => $res['dataProvider'],
    			'user_model'  => $user_model,
    			'refund_amount'=>$res['refund_amount'],
    			]);
    }
   //线下支付的退款 
    public function actionOfflineRefund()
    { 	 
    	if(\Yii::$app->user->can('offline-refund')){
	    	if (Yii::$app->request->isGet&&Yii::$app->request->get('id'))
	    	{
	    		$id=Yii::$app->request->get('id');	  	
	    		$model = LogRefund::find()->where(['refund_id'=>$id,'type'=>5,'state'=>2])->one();			
	    		$model->setScenario('offline_refund');
	    		if($model !== null){
	    			return $this->renderAjax('_form_offline_refund',[
		    				'id'=>$id,
		    				'url'=>Yii::$app->request->get('url'),
		    				'model'=>$model
		    				]);
	    		}else{
	    			throw new NotFoundHttpException('The requested page does not exist.');
	    		}
	    	}
	    	elseif (Yii::$app->request->isPost)
	    	{
	    		$id = Yii::$app->request->post('id');
	    		$model = LogRefund::find()->where(['refund_id'=>$id,'type'=>5,'state'=>2])->one();
	    		$model->setScenario('offline_refund');
	    		
	    		if ($model->load(Yii::$app->request->post()))
	    		{
	    			
	    			if($model->state==2 && $model->doing==3&& $model->type==5 ){
	    				$model->file = UploadedFile::getInstance($model, 'file');
		    			if(!empty($model->file)){
		    				$model->offline_file = Image::save_file($model);
		    			}

		    			$model->file = '';
		    			$logrefund = new LogRefund();		
		    			$logrefund->offline_refund($model);
		    			return $this->redirect(Yii::$app->request->post('url'));
	    			}
	    		}
	    	}
        }else{
        	throw new ForbiddenHttpException(Yii::t('app','Sorry , You don\'t have permission'));
        }
    }
}








